from typing import List, Optional
from uuid import UUID
from fastapi import HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from crud.remediations import (
    get_remediation,
    get_remediations_by_plan,
    create_remediation as crud_create_remediation,
    update_remediation as crud_update_remediation,
    update_remediation_status as crud_update_remediation_status,
    delete_remediation as crud_delete_remediation,
    delete_remediations as crud_delete_remediations
)
from schemas.remediations import (
    RemediationCreate, 
    RemediationUpdate, 
    RemediationStatusUpdate,
    RemediationStatus,
    RiskLevel
)
from models.remediations import RemediationItem
from log import log_info, log_error
from datetime import datetime

async def get_remediation_items_by_plan(
    db: AsyncSession, 
    plan_id: UUID, 
    skip: int = 0, 
    limit: int = 100,
    status: Optional[RemediationStatus] = None,
    risk_level: Optional[RiskLevel] = None
) -> List[RemediationItem]:
    """
    获取特定评估计划的所有整改项
    
    Args:
        db: 数据库会话
        plan_id: 评估计划ID
        skip: 跳过的记录数
        limit: 返回的最大记录数
        status: 按状态过滤
        risk_level: 按风险等级过滤
        
    Returns:
        整改项列表
    """
    log_info(f"获取计划 {plan_id} 的整改项列表", module="core.remediations")
    
    # 构建过滤条件
    filters = {}
    if status:
        filters["status"] = status
    if risk_level:
        filters["risk_level"] = risk_level
    
    # 调用CRUD函数获取数据
    return await get_remediations_by_plan(
        db=db, 
        plan_id=plan_id, 
        skip=skip, 
        limit=limit,
        filters=filters
    )

async def create_new_remediation_item(
    db: AsyncSession, 
    remediation: RemediationCreate
) -> RemediationItem:
    """
    创建新的整改项
    
    Args:
        db: 数据库会话
        remediation: 整改项创建模型
        
    Returns:
        创建的整改项
    """
    log_info("创建新整改项", module="core.remediations")
    
    # 可以在这里添加业务逻辑，例如验证、权限检查等
    # ...
    
    # 调用CRUD函数创建整改项
    return await crud_create_remediation(db=db, remediation=remediation)

async def update_remediation_item(
    db: AsyncSession, 
    remediation_id: UUID, 
    remediation: RemediationUpdate
) -> RemediationItem:
    """
    更新现有整改项
    
    Args:
        db: 数据库会话
        remediation_id: 整改项ID
        remediation: 整改项更新模型
        
    Returns:
        更新后的整改项
    """
    log_info(f"更新整改项: {remediation_id}", module="core.remediations")
    
    # 检查整改项是否存在
    db_remediation = await get_remediation(db, remediation_id=remediation_id)
    if db_remediation is None:
        log_error(f"整改项不存在: {remediation_id}", module="core.remediations")
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="整改项不存在")
    
    # 可以在这里添加业务逻辑，例如验证、权限检查等
    # ...
    
    # 调用CRUD函数更新整改项
    return await crud_update_remediation(db=db, db_remediation=db_remediation, remediation=remediation)

async def update_remediation_item_status(
    db: AsyncSession, 
    remediation_id: UUID, 
    status_update: RemediationStatusUpdate
) -> RemediationItem:
    """
    更新整改项状态
    
    Args:
        db: 数据库会话
        remediation_id: 整改项ID
        status_update: 状态更新模型
        
    Returns:
        更新后的整改项
    """
    log_info(f"更新整改项状态: {remediation_id}", module="core.remediations")
    db_remediation = await get_remediation(db, remediation_id)
    if not db_remediation:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="整改项不存在")
    
    db_remediation.status = status_update.status
    
    # 如果状态为已完成且未提供完成时间，则自动设置完成时间
    if status_update.status == RemediationStatus.COMPLETED:
        db_remediation.completion_date = datetime.utcnow()
    
    # 如果状态为进行中且未提供开始时间，则自动设置开始时间
    if status_update.status == RemediationStatus.IN_PROGRESS:
        db_remediation.completion_date = None
    
    await crud_update_remediation_status(db=db, remediation=db_remediation)
    
    return db_remediation

async def delete_remediation_item(
    db: AsyncSession, 
    remediation_id: UUID
) -> None:
    """
    删除整改项
    
    Args:
        db: 数据库会话
        remediation_id: 整改项ID
    """
    log_info(f"删除整改项: {remediation_id}", module="core.remediations")
    
    # 检查整改项是否存在
    db_remediation = await get_remediation(db, remediation_id=remediation_id)
    if db_remediation is None:
        log_error(f"整改项不存在: {remediation_id}", module="core.remediations")
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="整改项不存在")
    
    # 可以在这里添加业务逻辑，例如验证、权限检查等
    # ...
    
    # 调用CRUD函数删除整改项
    await crud_delete_remediation(db=db, db_remediation=db_remediation)

async def delete_multiple_remediation_items(
    db: AsyncSession, 
    remediation_ids: List[UUID]
) -> None:
    """
    批量删除整改项
    
    Args:
        db: 数据库会话
        remediation_ids: 要删除的整改项ID列表
    """
    if not remediation_ids:
        log_error("ID列表不能为空", module="core.remediations")
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="ID列表不能为空")
    
    log_info(f"批量删除整改项: {len(remediation_ids)}个", module="core.remediations")
    
    # 可以在这里添加业务逻辑，例如验证、权限检查等
    # ...
    
    # 调用CRUD函数批量删除整改项
    await crud_delete_remediations(db=db, remediation_ids=remediation_ids)
